package com.example.elemboot.Service.impl;

import com.example.elemboot.Dao.*;
import com.example.elemboot.Entity.*;
import com.example.elemboot.Service.IOrderService;
import com.example.elemboot.Utils.Result;
import jakarta.annotation.Resource;
import org.aspectj.weaver.ast.Or;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class OrderService implements IOrderService {
    @Resource
    private IOrders ordersDao;

    @Resource
    private ICart cartDao;

    @Resource
    private IBusiness businessDao;

    @Resource
    private IDeliveryAddress deliveryAddressDao;

    @Resource
    private IUser userDao;

    @Override
    public Orders createOrders(Double orderTotal, String userPhone, Integer daId, Integer businessId) {
        User user = userDao.findUserByUserPhone(userPhone);
        Business business = businessDao.findById(businessId).orElse(null);
        DeliveryAddress deliveryAddress = deliveryAddressDao.findById(daId).orElse(null);
        //先查询用户在本商家的购物车
        List<Cart> cartList = cartDao.findCartsByBusinessAndUser(business, user);
        //创建订单
        Orders orders = new Orders(orderTotal, business, deliveryAddress, user);
        //根据创建订单明细表
        List<OrderDetailet> orderDetailetList = new ArrayList<>();
        cartList.forEach(cart -> {
            OrderDetailet detailet = new OrderDetailet(cart.getQuantity(), cart.getFood());
            orderDetailetList.add(detailet);
        });
        //添加到订单
        orders.setOrderDetailetList(orderDetailetList);
        //持久化存储
        return ordersDao.save(orders);
    }

    @Override
    public List<Orders> listOrdersByUserId(String userPhone) {
        User user = userDao.findUserByUserPhone(userPhone);
        return ordersDao.findOrdersByUser(user);
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        return ordersDao.findById(orderId).orElse(null);
    }

    @Override
    public Boolean updateOrderState(Integer orderId) {
        Orders orders = ordersDao.findById(orderId).get();
        if (orders.getOrderState() == 1){
            return false;
        }
        orders.setOrderState(1);
        ordersDao.save(orders);
        return true;
    }
}
